<template>
  <BasicModal
    v-bind="$attrs"
    @register="registerModal"
    :title="modalTitle"
    @ok="onButtonOkClick"
    width="880px"
  >
    <BasicTable
      @register="registerProjectsTable"
      :can-resize="true"
      :bordered="true"
      :striped="true"
      :loading="false"
      :data-source="projectsData.projects"
    >
      <!-- 标记 -->
      <template #statusFlag="{ record }">
        <template v-if="record.flag === '0'">
          <Tag :color="'green'">启用</Tag>
        </template>
        <template v-if="record.flag === '5'">
          <Tag :color="'yellow'">禁用</Tag>
        </template>
        <template v-if="record.flag === '9'">
          <Tag :color="'red'">已删除</Tag>
        </template>
      </template>
    </BasicTable>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, reactive, unref, inject, provide } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';

  import { getUserProjects, setUserProjects } from '/@/api/project/user';
  import { projectsTableColumns } from '../user.data';

  import { useMessage } from '/@/hooks/web/useMessage';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { BasicTable, useTable } from '/@/components/Table';

  import { Tag } from 'ant-design-vue';

  const { createMessage } = useMessage();

  export default defineComponent({
    name: 'SetUserProjects',
    components: {
      BasicModal,
      BasicTable,
      Tag,
    },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const op = ref(OperationTypeEnum.UN_KNOWN);
      //标题--根据传入的模块名称+操作类型组合得到
      const modalTitle = ref('标题');
      const moduleName = inject<string>('moduleName');
      const tableTitle = ref('项目列表');

      const dataId = ref('');

      //勾选的项目id集合
      const pids = ref<number[] | string[]>([]);

      //处理过后的table数据
      const projectsData = reactive({
        checkedKeys: [],
        projects: [],
      });

      const [
        registerProjectsTable,
        { setSelectedRowKeys, getSelectRowKeys, clearSelectedRowKeys },
      ] = useTable({
        title: tableTitle,
        // api: getProjectUsers,
        columns: projectsTableColumns, //表头数据
        showTableSetting: true, //是否显示表格设置
        bordered: true,
        showIndexColumn: true,
        pagination: true, //关闭分页
        rowSelection: { type: 'checkbox' },
        rowKey: 'code',
        clickToRowSelect: false,
      });

      /**
       * 接收父组件传递的数据并处理
       */
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        //接收父组件传递的数据
        console.log(data);
        //判断是否传入op属性
        if (data?.op) {
          op.value = data.op;
        }

        if (data?.dataId) {
          dataId.value = data.dataId; //用户id
        }

        if (moduleName) {
          modalTitle.value = unref(moduleName);
        }
        if (op.value != OperationTypeEnum.UN_KNOWN && op.value != OperationTypeEnum.CUSTOME) {
          modalTitle.value += '--' + op.value;
        }

        setModalProps({ confirmLoading: false });

        getProjects();

        //后台返回的数据如果有已经关联的则设置选中行
        setSelectedRowKeys(projectsData.checkedKeys);
      });

      /**
       * 获取用户项目信息
       */
      async function getProjects() {
        //每次打开窗口都会重复加载数据，在加载数据前如果有数据先清空
        if (projectsData.projects.length > 0) {
          projectsData.projects = [];
          projectsData.checkedKeys = [];
        }
        //调用后端接口获取数据
        getUserProjects(dataId.value)
          .then((res) => {
            console.log('res', res);
            //处理返回数据
            res.forEach((val) => {
              projectsData.projects.push(val.project);
              //获取设置项目之前已经关联的项目编码，用于回显勾选
              if (val.checked === true) {
                projectsData.checkedKeys.push(val.project.code);
              }
            });
            console.log('projectsData', projectsData);
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      /**
       * 点击确认按钮，调用接口保存关联信息
       */
      async function onButtonOkClick() {
        //获取设置选中的项目id集合
        pids.value = getSelectRowKeys();
        console.log('pids', pids.value);
        try {
          setModalProps({ confirmLoading: true });
          //调用接口进行保存
          setUserProjects({ userid: dataId.value, pids: pids.value })
            .then((res) => {
              if (!res || Object.keys(res).length == 0) {
                createMessage.success('设置成功', 2);
              }
              closeModal();
              emit('success');
            })
            .catch((ex) => {
              console.log('catch ', ex);
              createMessage.error(ex.msg);
            });
        } finally {
          setModalProps({ confirmLoading: false });
        }
        // 清空选中的行;
        clearSelectedRowKeys();
      }

      return {
        op,
        moduleName,
        modalTitle,
        // UsersModuleName,
        registerModal,
        registerProjectsTable,
        getProjects,

        projectsData,
        onButtonOkClick,
      };
    },
  });
</script>
